package com.jinke.uang.ui.activity.personal;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.location.Location;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.jinke.uang.BuildConfig;
import com.jinke.uang.R;
import com.jinke.uang.adapter.ProductTermAdapter;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseObserable;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.bean.MoneyProductData;
import com.jinke.uang.bean.TimeProductData;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.cache.Acache;
import com.jinke.uang.cache.AcacheKeys;
import com.jinke.uang.common.UserAuthRouter;
import com.jinke.uang.common.UserInfo;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.bean.AuthData;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.http.ParamsFactory;
import com.jinke.uang.http.RetrofitManager;
import com.jinke.uang.http.Urls;
import com.jinke.uang.model.BorrowModule;
import com.jinke.uang.permission.IPermisson;
import com.jinke.uang.permission.Permission;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.bean.CalculateData;
import com.jinke.uang.bean.JsOrderData;
import com.jinke.uang.ui.webview.WebViewActivity;
import com.jinke.uang.utils.LocationUtils;
import com.jinke.uang.utils.StringUtils;
import com.jinke.uang.utils.ToastUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 借款详情界面
 */
@Route(name = "借款详情", path = RouterMap.BORROW_PAGE)
public class BorrowActivity extends BaseNormalActivity <CommonPresenter,BorrowModule> implements IPermisson,
        ProductTermAdapter.OnProductTermListener {

    public static final String KEY_OF_BORROW_MONEY = "repayment_page_borrow_money";
    public static final String KEY_OF_PID = "repayment_page_pid";

    /**
     * 传输的 产品数据
     */
    public static final String MONEY_DATA = "money_data";

    @BindView(R.id.recycler_view_product_term)
    RecyclerView recyclerViewProductTerm;
    private ProductTermAdapter productTermAdapter;
    private List<TimeProductData> productItemTermList;

    @BindView(R.id.tv_loan_of_num)
    TextView tv_loan_of_num;
    @BindView(R.id.tv_loan_of_life)
    TextView tv_loan_of_life;
    @BindView(R.id.tv_detail_interest_hint)
    TextView tv_detail_interest_hint;
    @BindView(R.id.tv_detail_interest)
    TextView tv_detail_interest;

    @BindView(R.id.tv_detail_credit_service_fee_hint)
    TextView tv_detail_credit_service_fee_hint;
    @BindView(R.id.tv_detail_credit_service_fee)
    TextView tv_detail_credit_service_fee;

    @BindView(R.id.tv_detail_account_management_fee_hint)
    TextView tv_detail_account_management_fee_hint;
    @BindView(R.id.tv_detail_account_management_fee)
    TextView tv_detail_account_management_fee;

    @BindView(R.id.tv_detail_time_out)
    TextView tv_detail_time_out;
    @BindView(R.id.tv_real_pay)
    TextView tv_real_pay;

    @BindView(R.id.check_agreement)
    CheckBox checkAgreement;

    private String mBorrowMoney;
    private String mPid;
    private CalculateData borrowDetail;

    private MoneyProductData oneMoney;

    private String addressBookUuid;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void onUIReady() {
        oneMoney = (MoneyProductData) getIntent().getSerializableExtra(MONEY_DATA);
        if (null != oneMoney) {
            productItemTermList = oneMoney.getProdDetailDTOList();
            String moneyUnit = getResources().getString(R.string.money_unit);
            tv_loan_of_num.setText(moneyUnit + StringUtils.getDotMoneyStr(oneMoney.getProdRange()));
        }
        if (productItemTermList == null || productItemTermList.size() < 1) {
            ToastUtils.showShort(this, getStringResource(R.string.illegal_params));
            finish();
            return;
        }
        TimeProductData productItemData = productItemTermList.get(0);
        mBorrowMoney = String.valueOf(oneMoney.getProdRange());
        mPid = productItemData.getPId();
        RecyclerView.LayoutManager lm;
        if(productItemTermList.size()>2){
           lm = new GridLayoutManager(this, 3);
        }else {
            lm = new GridLayoutManager(this, 2);
        }
        recyclerViewProductTerm.setLayoutManager(lm);
        productTermAdapter = new ProductTermAdapter(this, this);
        recyclerViewProductTerm.setAdapter(productTermAdapter);

        mPresenter.getData(HttpConstant.PRODUCT_DATA,null,mBorrowMoney, mPid);
        productTermAdapter.addItems(productItemTermList);
    }



    @Override
    protected int getContentResId() {
        return R.layout.activity_borrow;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.borrow_title);
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected BorrowModule getModule() {
        return new BorrowModule();
    }

    @OnClick(R.id.btn_update_num)
    public void updateNum() {
        finish();
    }

    //确认提交借款
    @OnClick(R.id.btn_confirm_submit)
    public void confirmSubmit() {
        if (!checkAgreement.isChecked()) {
            ToastUtils.showShort(BorrowActivity.this, getStringResource(R.string.borrow_not_agree));
            return;
        }
        showLoadingView();
        mPresenter.getData(HttpConstant.CHECK_ORDER_QUALIFICATIONS,null);
    }

    @OnClick({R.id.tv_check_agreement_text})
    public void weburl() {
        if (borrowDetail == null || StringUtils.isEmpty(mBorrowMoney)) {
            mPresenter.getData(HttpConstant.PRODUCT_DATA,null,mBorrowMoney, mPid);
            return;
        }
        JsOrderData orderData = new JsOrderData();
        orderData.setBorrowMoney(mBorrowMoney);
        orderData.setBorrowDay(borrowDetail.getPTerm());
        orderData.setToken(UserInfo.getToken());
        ARouter.getInstance().build(RouterMap.WEB_VIEW_PAGE).withString(WebViewActivity
                .PARAMS_URL, Urls.REGISTER_CONTRACT_URL).withSerializable(WebViewActivity
                .PARAMS_ORDER_DATA, orderData).navigation();
        checkAgreement.setChecked(true);
    }

    @SuppressLint("SetTextI18n")
    private void fillDetailUI(CalculateData data) {
        borrowDetail = data;
        Resources resources = BorrowActivity.this.getResources();
        String moneyUnit = getResources().getString(R.string.money_unit);
        String dayUnit = getResources().getString(R.string.day_unit_hint);

        tv_loan_of_life.setText(data.getPTerm() + dayUnit);
        tv_detail_interest_hint.setText(String.format(resources.getString(R.string
                .loan_detail_interest), data.getPInterest()));
        tv_detail_interest.setText(moneyUnit + StringUtils.getDotMoneyStr(data.getTotalInterest()));
        tv_detail_credit_service_fee_hint.setText(String.format(resources.getString(R.string
                .loan_detail_credit_service_fee), data.getPCreditserviceFee()));
        tv_detail_credit_service_fee.setText(moneyUnit + StringUtils.getDotMoneyStr(data
                .getTotalCreditserviceFee()));
        tv_detail_account_management_fee_hint.setText(String.format(resources.getString(R.string
                .loan_detail_account_management_fee), data.getPAccountFee()));
        tv_detail_account_management_fee.setText(moneyUnit + StringUtils.getDotMoneyStr(data
                .getTotalAccountFee()));
        tv_detail_time_out.setText(moneyUnit + StringUtils.getDotMoneyStr(data.getExpiryReturned
                ()));
        tv_real_pay.setText(moneyUnit + StringUtils.getDotMoneyStr(data.getNeteceipts()));
    }

    @Override
    public void onProductTermClick(View view, int position) {
        if("2".equals(productItemTermList.get(position).getStatus())){
            ToastUtils.showShort(BorrowActivity.this, getResources().getString(R.string
                    .loan_level_too_low));
        }else{
            mPid = productItemTermList.get(position).getPId();
            showLoadingView();//计算利率耗时，显示进度条，页面不可点击
            mPresenter.getData(HttpConstant.PRODUCT_DATA,null,mBorrowMoney, mPid);
        }
    }

    //返回值
    @Override
    public void showResponse(int apiType,String listType, Object o) {
        if(apiType==HttpConstant.PRODUCT_DATA){//计算利率接口
            dismissLoadingView();
            BaseResponse<CalculateData> calculateResponse = (BaseResponse<CalculateData>) o;
            if (calculateResponse.getStatus() == 200) {
                fillDetailUI(calculateResponse.getData());
            } else {
                ToastUtils.showShort(BorrowActivity.this, calculateResponse.getMessage());
            }
        }

        else if(apiType==HttpConstant.CREATE_ORDER){ //产品提单接口
            dismissLoadingView();
            BaseResponse<String> baseResponse = (BaseResponse<String>) o;
            if (baseResponse.getStatus() == Constant.HTTP_OK) {
                //申请完成
                ARouter.getInstance().build(RouterMap.STATUS_DISPLAY).withInt(StatusDisplayActivity
                        .PAGE_TYPE_KEY, 1).navigation();
                finish();
            } else {
                //提交
                ToastUtils.showShort(BorrowActivity.this, baseResponse.getMessage());
            }
        }

        else if(apiType==HttpConstant.CHECK_ORDER_QUALIFICATIONS){//判断是否可以提单接口
            dismissLoadingView();
            BaseResponse<String> baseResponse = (BaseResponse<String>) o;
            if (baseResponse.getStatus() == Constant.HTTP_OK) {
                mPresenter.getData(HttpConstant.AUTH_STATUS,null);
            } else {
                ToastUtils.showShort(this, baseResponse.getMessage());
            }
        }

        else if(apiType==HttpConstant.AUTH_STATUS){//查询认证状态
            dismissLoadingView();
            BaseResponse<AuthData> authResponse = (BaseResponse<AuthData>) o;
            addressBookUuid = authResponse.getData().getAddressBookUuid();
            if (authResponse.getStatus() == Constant.HTTP_OK) {
                Acache.get(this).put(AcacheKeys.AUTH, new Gson().toJson(authResponse.getData(), AuthData
                        .class));
            //1未认证，2通过
                if (authResponse.getData().getStatus() == 2) {
                    mPresenter.getData(HttpConstant.CREATE_ORDER,null,borrowDetail.getExpiryReturned(), borrowDetail.getPId
                            (),authResponse.getData().getAddressBookUuid());

                    //上传位置信息的
                    Permission permission = new Permission(this, this);
                    permission.uploadLocation();
                } else {
                    UserAuthRouter.getInstance().jump2FirstNotAuthPager();
                }
            } else {
                ToastUtils.showShort(this, authResponse.getMessage());
            }
        }
    }

    @Override
    public void showError(Throwable e) {
        dismissLoadingView();
    }

    @Override
    public void onSuccess(int result) {

    }

    //获取地理位置信息
    @Override
    public void onSuccess(Object object) {
        Location location = LocationUtils.getLocation(this);
        if (location == null) return;
        Map<String, Object> formMap = new HashMap<String, Object>();
        formMap.put("longitude", String.valueOf(location.getLongitude()));
        formMap.put("latitude", String.valueOf(location.getLatitude()));
        formMap.put("saveType", "2");
        formMap.put("userPhone", "");
        formMap.put("userUuid",UserInfo.getSaveUuid());
        formMap.put("addressBookUuid",addressBookUuid);

        RetrofitManager.getInstance().getINetService().uploadLocationRegister(BuildConfig.channel, UserInfo.getToken(), ParamsFactory
                .getCommonParams(formMap)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserable() {
                    @Override
                    protected void onBaseNext(Object value) {
                    }

                    @Override
                    protected void onBaseError(Throwable e) {
                    }
                });
    }
}
